import { RequestOptions, EnvConfig } from './request.type';

const envConfig: EnvConfig = {
  dev: 'http://116.198.196.77:8080', // 开发环境
  test: 'http://test.example.com', // 测试环境
  prod: 'http://prod.example.com' // 生产环境
};

const env: string = 'dev';
const baseURL: string = envConfig[env];

// 请求拦截器
uni.addInterceptor('request', {
  invoke: (options: any) => {
    // 加token
    const token = uni.getStorageSync('token');
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      };
    }
    // loading
    uni.showLoading({
      title: '加载中...'
    });
    console.log('请求拦截器', options);
  },
  success: (res: any) => {
    console.log('请求成功', res);
  },
  fail: (err: any) => {
    console.log('请求失败', err);
  },
  complete: () => {
    uni.hideLoading();
  }
});

// 响应拦截器
uni.addInterceptor('request', {
  success: (res: any) => {
    console.log('响应拦截器成功', res);
    if (res.statusCode !== 200) {
      uni.showToast({
        title: res.data.message || '请求失败',
        icon: 'none'
      });
      return Promise.reject(res.data);
    }
    return res;
  },
  fail: (err: any) => {
    console.log('响应拦截器失败', err);
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    });
    return Promise.reject(err);
  }
});

const request = (url: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET', data: any = {}, header: any = {}, timeout: number = 30000): Promise<any> => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseURL + url,
      method: method,
      data: data,
      header: header,
      timeout: timeout,
      success: (res: any) => {
        uni.hideLoading();
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          uni.showToast({
            title: res.data.message || '请求失败',
            icon: 'none'
          });
          reject(res.data);
        }
      },
      fail: (err: any) => {
        uni.hideLoading();
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        reject(err);
      }
    });
  });
};

export default request;
